package com.github.rxyor.common.support.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/11/14 周四 13:12:00
 * @since 1.0.0
 */
public class HttpServletUtil {

    private HttpServletUtil() {
    }

    /**
     * copy from internet
     *
     * @param request
     * @return
     */
    public static String parseIpFromRequest(HttpServletRequest request) {
        Preconditions.checkArgument(request != null, "request can't be null");
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.startsWith("unknown")) {
            ip = ip.substring(ip.indexOf("unknown") + "unknown".length());
        }
        ip = ip.trim();
        if (ip.startsWith(",")) {
            ip = ip.substring(1);
        }
        if (ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }

    public static void writeDataToResponse(HttpServletResponse response, Object data) throws IOException {
        Preconditions.checkArgument(response != null, "response can't be null");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(data, SerializerFeature.WriteMapNullValue));
    }
}
